<template>
  <el-card style="margin:20px;height: 70px;">
    <el-form :inline="true">
      <el-form-item>
        <el-select v-model="searchFilmFrom.filmId"
                   clearable
                   filterable
                   style="width:240px;"
                   placeholder="请输入电影名称">
          <el-option
              v-for="item in filmData"
              :label="item.filmName"
              :value="item.id">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button @click="resetSearch">重置</el-button>
        <el-button type="primary" @click="searchCarousel">搜索</el-button>
      </el-form-item>
      <el-button type="primary" @click="allCarouselDetails"
                 style="margin-right: 20px;float: right">查看详情
      </el-button>
      <el-button type="success" @click="addCarousel"
                 style="margin-right: 20px;float: right">新增
      </el-button>
    </el-form>
  </el-card>


  <el-card style="margin:20px;">
    <div style="margin:10px 0 40px 10px;">
      <el-radio-group v-model="status">
        <el-radio-button value="1" @change="searchCarousel">启用</el-radio-button>
        <el-radio-button value="0" @change="searchCarousel">禁用</el-radio-button>
      </el-radio-group>
    </div>
    <el-row :gutter="20">
      <el-col :span="16">
        <el-table :data="paginatedData"
                  style="height: 445px;">
          <el-table-column type="index" label="编号" width="80" align="center"/>
          <el-table-column prop="filmName" label="电影名称" align="center"/>
          <el-table-column v-if="status === '1'" prop="sort" label="顺序" align="center"/>
          <el-table-column prop="status" label="状态" align="center">
            <template #default="scope">
          <span v-if="scope.row.status === '1'"
                type="success">启用
          </span>
              <span v-if="scope.row.status === '0'"
                    type="danger">禁用
          </span>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center">
            <template #default="scope">
              <el-button link type="primary"
                         @click="editCarousel(scope.row.id)">编辑
              </el-button>
              <el-button link type="danger"
                         @click="deleteCarousel(scope.row.id)">删除
              </el-button>
              <el-button link type="primary"
                         @click="carousel(scope.row.id)">
                海报
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination
            v-model:current-page="currentPage"
            :page-size="pageSize"
            layout="total, prev, pager, next, jumper"
            :total="tableData.length"
            @current-change="handlePageChange"
            style="margin-top:20px;margin-left:  35%"
        />
      </el-col>
      <el-col :span="8">
        <el-carousel
            direction="vertical"
            type="card"
            :autoplay="false"
        >
          <el-carousel-item v-for="item in carouselData" :key="item">
            <img :src="BASE_URL + item.poster"
                 style="width: 100%;"
                 alt="">
          </el-carousel-item>
        </el-carousel>
      </el-col>
    </el-row>
  </el-card>

  <el-dialog :title="cancelTitle"
             :before-close="cancelCarousel"
             style="width:560px;height: 460px; padding:30px;"
             v-model="carouselVisible">
    <el-form label-width="100">
      <el-form-item label="电影名称">
        <el-select v-model="saveCarouselFrom.filmId"
                   clearable
                   filterable
                   style="width:90%;"
                   placeholder="请输入电影名称">
          <el-option
              v-for="item in filmData"
              :label="item.filmName"
              :value="item.id">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="顺序">
        <el-input v-model="saveCarouselFrom.sort"
                  placeholder="请输入顺序"
                  style="width:90%;"/>
      </el-form-item>
      <el-form-item label="状态">
        <el-radio-group v-model="saveCarouselFrom.status">
          <el-radio label="1">启用</el-radio>
          <el-radio label="0">禁用</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="轮播图">
        <el-upload
            v-model:file-list="carouselList"
            v-model:action="actionUrl"
            name="file"
            limit="1"
            list-type="picture-card"
            :on-preview="handlePictureCardPreview"
            :on-remove="handleRemove"
        >
          <el-icon>
            <Plus/>
          </el-icon>
        </el-upload>
        <el-dialog v-model="dialogVisible">
          <img :src="dialogImageUrl"
               :alt="dialogImageUrl"/>
        </el-dialog>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="cancelCarousel">取消</el-button>
      <el-button type="primary" @click="saveCarousel">保存</el-button>
    </template>
  </el-dialog>

  <el-dialog
      style="width:560px;height: 330px; padding:30px;"
      v-model="carouselDetailsVisible">
    <el-image v-if="carouselDetailsVisible"
              :src="BASE_URL + carouselDetails"
              style="width: 100%;"
              alt="">
    </el-image>
  </el-dialog>

  <el-dialog
      style="width: 1260px; height:auto; padding:30px;"
      v-model="allCarouselDetailsVisible">
    <div style="height: 400px;position: relative;overflow: hidden;">
      <!-- 主图片展示 -->
      <div>
        <img :src="currentImageUrl" alt="Main Image" style=" float: right;
              width: 800px;
              height: 400px;
              border-radius: 10px;"/>
      </div>

      <div style="width: 600px; position: absolute; bottom: 50px;right: -100px; z-index: 2;">
        <el-carousel :interval="5000" type="card" indicator-position="none"
                     style="height: 100px;margin: 0 auto;"
                     arrow="never" @change="handleCarouselChange">
          <el-carousel-item v-for="(item, index) in carouselData" :key="index" style=" .el-carousel__item--card {
                              background-color: transparent;
                              margin-left: 20px;
                              width: 156px;
                              height: 96px;
                            }">
            <img :src="BASE_URL + item.poster" style="   width: 150px;height: 90px; border: 2px solid #FFFFFF;"
                 alt="Thumbnail" @click="changeCarousel(index)"/>
          </el-carousel-item>
        </el-carousel>
      </div>
      <div style=" display: flex;align-items: center;position: absolute;
                   z-index: 1; bottom: 0;left: 0; width: 1200px; height: 400px;
                   background: linear-gradient(115deg, #0f1827 40%, rgba(15, 24, 39, 0) 70%);
                   border-top-left-radius: 10px;
                   border-bottom-left-radius: 10px;">
        <div class="content">
          <p class="title">{{ filmName }}</p>
          <p>{{ englishName }}</p>
          <p>{{ regionFormatter(regionList, null, region) }} </p>
          <p>{{ releaseDate }} 上映 </p>
        </div>
        <el-button type="primary"
                   disabled
                   style="position: absolute;bottom: 40px;left: 100px;width: 200px;
                          height: 40px;background-color: #671523;border-radius: 30px;color: #fff;font-size: 16px;
                          font-weight: bold;border: transparent;">
          <el-icon style="font-size: 20px;margin-right: 5px;font-weight: bold;">
            <VideoPlay/>
          </el-icon>
          观看视频
        </el-button>
      </div>
    </div>


  </el-dialog>

</template>

<script setup>
import {computed, onMounted, ref} from "vue";
import qs from "qs";
import axios from "axios";
import {ElMessage, ElMessageBox} from "element-plus";

const tableData = ref([]);
const currentPage = ref(1);// 默认显示页码
const pageSize = ref(10); // 每页显示几条

// 计算当前页面的数据
const paginatedData = computed(() => {
  const offset = (currentPage.value - 1) * pageSize.value;
  return tableData.value.slice(offset, offset + pageSize.value);
});

// 分页变化时触发
const handlePageChange = (newPage) => {
  currentPage.value = newPage;
};

const filmData = ref([]);

const searchFilm = () => {
  axios.get(BASE_URL + '/v1/film/select?')
      .then((response) => {
        if (response.data.code === 2000) {
          filmData.value = response.data.data;
        } else {
          ElMessage({
            message: response.data.msg,
            type: 'error',
            showClose: true,
            center: true,
          });
        }
      });
}
onMounted(() => {
  searchFilm();
})
const status = ref('1');
const searchFilmFrom = ref({
  filmId: '',
});
const searchCarousel = () => {
  searchFilmFrom.value.status = status.value;
  let data = qs.stringify(searchFilmFrom.value);
  axios.get(BASE_URL + '/v1/carousel/select?' + data)
      .then((response) => {
        if (response.data.code === 2000) {
          tableData.value = response.data.data;
          console.log(response.data.data);
        } else {
          ElMessage({
            message: response.data.msg,
            type: 'error',
            showClose: true,
            center: true,
          });
        }
      });
}
onMounted(() => {
  searchCarousel();
})
const resetSearch = () => {
  searchFilmFrom.value = {
    filmId: '',
  };
  searchCarousel();
}
const cancelTitle = ref('添加轮播图');
const carouselVisible = ref(false);
const addCarousel = () => {
  carouselVisible.value = true;
}
const saveCarouselFrom = ref({
  filmId: '',
  sort: '',
  status: '1',
});
/**图片上传相关代码开始**/
const carouselList = ref([]);
const dialogImageUrl = ref('');
const dialogVisible = ref(false);
//定义变量用来保存图片上传给哪个后端接口地址
const actionUrl = ref(BASE_URL + '/v1/carousel/upload');
//移除图片
const handleRemove = (uploadFile, uploadFiles) => {
  let carouselListUrl = uploadFile.response.data;
  //2.给后端发请求,删除图片
  axios.post(BASE_URL + '/v1/carousel/remove?carouselListUrl=' + carouselListUrl)
      .then((response) => {
        if (response.data.code === 2000) {
          ElMessage.success('删除成功!');
        }
      })
}
//图片上传后预览
const handlePictureCardPreview = (uploadFile) => {
  dialogImageUrl.value = uploadFile.url
  dialogVisible.value = true;
}
/**图片上传相关代码结束**/
const saveCarousel = () => {
  if (saveCarouselFrom.value.filmId === '' || saveCarouselFrom.value.filmId === null) {
    errorInfo('请选择电影');
    return;
  }
  if (saveCarouselFrom.value.sort === '' || saveCarouselFrom.value.sort === null) {
    errorInfo('请输入顺序');
    return;
  }
  if (carouselList.value.length === 0) {
    errorInfo('请上传图片');
    return;
  }
  saveCarouselFrom.value.poster = carouselList.value[0].response.data;
  let data = qs.stringify(saveCarouselFrom.value);
  axios.post(BASE_URL + '/v1/carousel/save', data)
      .then((response) => {
        if (response.data.code === 2000) {
          OKInfo('保存成功!');
          carouselVisible.value = false;
          searchCarousel();
          carouselByStatus();
          saveCarouselFrom.value = {
            filmId: '',
            sort: '',
            status: '1',
          };
          carouselList.value = [];
        } else {
          ElMessage({
            message: response.data.msg,
            type: 'error',
            showClose: true,
            center: true,
          });
        }
      });
}
const cancelCarousel = () => {
  ElMessageBox.confirm('确认取消吗？', '提示', {
    customClass: 'custom-message-box',
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(() => {
    Info('已取消保存');
    carouselVisible.value = false;
    saveCarouselFrom.value = {
      filmId: '',
      sort: '',
      status: '1',
    };
    carouselList.value = [];
  }).catch(() => {

  });
}
const editCarousel = (id) => {
  carouselVisible.value = true;
  cancelTitle.value = '修改信息';
  axios.get(BASE_URL + '/v1/carousel/select?id=' + id)
      .then((response) => {
        if (response.data.code === 2000) {
          saveCarouselFrom.value = response.data.data[0];
          carouselList.value = [
            {
              url: BASE_URL + saveCarouselFrom.value.poster,
              response: {
                data: saveCarouselFrom.value.poster
              }
            }
          ];
        } else {
          ElMessage({
            message: response.data.msg,
            type: 'error',
            showClose: true,
            center: true,
          });
        }
      });
}
const carouselData = ref([]);
const carouselByStatus = () => {
  let data = qs.stringify({
    status: 1
  });
  axios.get(BASE_URL + '/v1/carousel/select?' + data)
      .then((response) => {
        if (response.data.code === 2000) {
          carouselData.value = response.data.data;
          if (carouselData.value.length > 0) {
            changeCarousel(0)
          }
        } else {
          ElMessage({
            message: response.data.msg,
            type: 'error',
            showClose: true,
            center: true,
          });
        }
      });
}
onMounted(() => {
  carouselByStatus();
})

const deleteCarousel = (id) => {
  ElMessageBox.confirm('确认删除吗？', '提示', {
    customClass: 'custom-message-box',
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(() => {
    axios.delete(BASE_URL + '/v1/carousel/delete/' + id)
        .then((response) => {
          if (response.data.code === 2000) {
            OKInfo('删除成功!')
            searchCarousel();
            carouselByStatus();
            saveCarouselFrom.value = {
              filmId: '',
              sort: '',
              status: '1',
            };
            carouselList.value = [];
          }
        });
  }).catch(() => {
    Info('已取消删除');
  });
}
const carouselDetailsVisible = ref(false);
const carouselDetails = ref([])
const carousel = (id) => {
  carouselDetailsVisible.value = true;
  axios.get(BASE_URL + '/v1/carousel/select?id=' + id)
      .then((response) => {
        if (response.data.code === 2000) {
          carouselDetails.value = response.data.data[0].poster;
          console.log(carouselDetails.value)
        } else {
          ElMessage({
            message: response.data.msg,
            type: 'error',
            showClose: true,
            center: true,
          });
        }
      });
}
const allCarouselDetailsVisible = ref(false);
const allCarouselDetails = () => {
  allCarouselDetailsVisible.value = true;
}
const regionList = ref([]);
onMounted(() => {
  loadDictOptions(regionList, 'nationality');
});

const regionFormatter = (row, column, cellValue, index) => {
  if (!regionList.value) {
    return cellValue;
  }
  for (let item of regionList.value) {
    if (item.value === cellValue) {
      cellValue = item.label;
    }
  }
  return cellValue;
}
const currentImageUrl = ref('');

const changeCarousel = (index) => {
  currentImageUrl.value = BASE_URL + carouselData.value[index].poster;
  updateCurrentImage(index)
}
const handleCarouselChange = (newIndex) => {
  changeCarousel(newIndex);
  updateCurrentImage(newIndex)
}

const filmName = ref(''); // 当前图片的标题
const englishName = ref('');
const region = ref('');
const releaseDate = ref('');
const filmId = ref('');
const updateCurrentImage = (index) => {
  const currentItem = carouselData.value[index];
  filmName.value = currentItem.filmName;
  englishName.value = currentItem.englishName;
  region.value = currentItem.region;
  releaseDate.value = currentItem.releaseDate;
  filmId.value = currentItem.filmId;
}
</script>

<style scoped>
.content {
  position: absolute;
  top: 5%;
  left: 90px;
  font-size: 20px;
  color: #fff;

  p {
    margin-bottom: 10px;
  }
}

.title {
  font-size: 40px;
  font-weight: bold;
}


</style>